//
//  DDShoppintCartViewController.m
//  Dingdong
//
//  Created by 程强 on 16/11/11.
//  Copyright © 2016年 程强. All rights reserved.
//

#import "DDShoppintCartViewController.h"
#import "DDCartTableCell.h"
#import "DDCartSectionHeader.h"
#import "DDGoodsDetailsViewController.h"
#import "MJRefresh.h"
#import "DDCreateOrderViewController.h"
#import "DDNavigationController.h"
#import "DDCartManager.h"
#import "DDCartSet.h"
#import "UIAlertView+Click.h"
#import "DDHomeManager.h"
#import "DDHotSaleSet.h"
#import "DDCartHotSaleCollectionCell.h"
#import "DDHotSaleCollectionHeaderView.h"
#import "DDHotSaleCollectionCustomeHeaderView.h"

typedef NS_ENUM(NSInteger, DingDongCartStatus) {
    DingDongCartStatusCheckOut = 0,
    DingDongCartStatusEdit,
};

@interface DDShoppintCartViewController ()<UITableViewDelegate,UITableViewDataSource,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UIAlertViewDelegate>
@property (weak, nonatomic) IBOutlet UITableView *cartTable;
@property (strong, nonatomic) UIView *unLoginView;
@property (strong, nonatomic) UIView *cartEmptyView;

#pragma mark --- 结算view
@property (weak, nonatomic) IBOutlet UIView *checkoutView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *checkoutViewHeight;
@property (weak, nonatomic) IBOutlet UIButton *checkSelectBtn;
@property (weak, nonatomic) IBOutlet UILabel *checkTotalLbl;
@property (assign, nonatomic) CGFloat totalMoney;
@property (weak, nonatomic) IBOutlet UIButton *checkoutBtn;
@property (assign, nonatomic) BOOL checkAllSelectStatus;
#pragma mark --- 编辑view
@property (weak, nonatomic) IBOutlet UIView *editView;
@property (weak, nonatomic) IBOutlet UIButton *editSelectBtn;
@property (assign, nonatomic) BOOL editAllSelectStatus;
#pragma mark --- 选中的商品
@property (assign, nonatomic) DingDongCartStatus cartStatus;
@property (strong, nonatomic) NSMutableDictionary *selectedDic;

#pragma mark --- 测试热卖view
@property (strong, nonatomic) UIView *hotFooterView;
@property (strong, nonatomic) UICollectionView *hotCollection;
@property (strong, nonatomic) DDCartManager *manager;
@property (strong, nonatomic) DDHomeManager *homeManager;
@property (assign, nonatomic) NSInteger currentPage;
@property (strong, nonatomic) DDHotSaleSet *hotSet;
#pragma mark --- 数据源
@property (strong, nonatomic) DDCartSet *cartSet;
@end

@implementation DDShoppintCartViewController
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if ([SystemConfig shareInstance].isLogin) {
        [self.unLoginView removeFromSuperview];
        self.unLoginView = nil;
        UIView *tableViewHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, ScreenWidth, CGFLOAT_MIN)];
        self.cartTable.tableHeaderView = tableViewHeaderView;
        self.checkoutView.hidden = NO;
        [self fetchCartList];
    }
}
- (void)setRightItemBar
{
    if (!self.navigationItem.rightBarButtonItem) {
        UIBarButtonItem *rightBar = [[UIBarButtonItem alloc]initWithTitle:@"Edit" style:UIBarButtonItemStylePlain target:self action:@selector(editShopCartClick)];
        rightBar.tintColor = [UIColor darkGrayColor];
        self.navigationItem.rightBarButtonItem = rightBar;
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.manager = [DDCartManager new];
    self.homeManager = [DDHomeManager new];
    [self layoutCartView];
    [self checkCartLogin];
}
- (void)checkCartLogin
{
    if (![SystemConfig shareInstance].isLogin) {
        
        if (!_unLoginView) {
            self.unLoginView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 65)];
            _unLoginView.backgroundColor = [UIColor whiteColor];
            self.cartTable.tableHeaderView = _unLoginView;
            
            UIButton *loginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            [loginBtn setTitle:@"Sign in" forState:UIControlStateNormal];
            [_unLoginView addSubview:loginBtn];
            [loginBtn addTarget:self action:@selector(loginInClick:) forControlEvents:UIControlEventTouchUpInside];
            [loginBtn setTitleColor:RGBColor(168, 167, 167) forState:UIControlStateNormal];
            loginBtn.layer.borderColor = RGBColor(255, 145, 147).CGColor;
            loginBtn.layer.borderWidth = 1.0;
            loginBtn.layer.cornerRadius = 3.0;
            [loginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.width.equalTo(@90);
                make.height.equalTo(@40);
                make.centerY.equalTo(_unLoginView);
                make.left.equalTo(@40);
            }];
            
            KKLabel *contentLbl = [[KKLabel alloc]initWithBlock:^(KKLabel *lbl) {
                lbl.laText(@"Please sign in after shopping.",RGBColor(174, 174, 174),[UIFont systemFontOfSize:15.0],NSTextAlignmentLeft);
            }];
            [_unLoginView addSubview:contentLbl];
            [contentLbl mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(_unLoginView);
                make.left.equalTo(loginBtn.mas_right).offset(10);
                make.height.equalTo(@30);
                make.right.equalTo(_unLoginView).offset(-20);
            }];

            KKLabel *line = [[KKLabel alloc]initWithBlock:^(KKLabel *lbl) {
                
            }];
            line.backgroundColor = RGBColor(237, 237, 237);
            [_unLoginView addSubview:line];
            [line mas_makeConstraints:^(MASConstraintMaker *make) {
                make.width.equalTo(_unLoginView);
                make.height.equalTo(@1);
                make.bottom.equalTo(_unLoginView).offset(0);
                make.centerX.equalTo(_unLoginView);
            }];
        }
        self.checkoutView.hidden = YES;
        self.editView.hidden = YES;
        self.checkoutViewHeight.constant = 0;
    }
}
- (void)checkCartEmpty
{
    if (self.cartSet.cartAry.count == 0) {
        [self cartEmptyTopView];
        self.checkoutView.hidden = YES;
        self.editView.hidden = YES;
        self.checkoutViewHeight.constant = 0;
        self.navigationItem.rightBarButtonItem = nil;
    }else{
        [self.cartEmptyView removeFromSuperview];
        self.cartEmptyView = nil;
    }
}
- (void)cartEmptyTopView
{
    if (!_cartEmptyView) {
        self.cartEmptyView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 65)];
        _cartEmptyView.backgroundColor = [UIColor whiteColor];
        
        UIImageView *cartIcon = [[UIImageView alloc]initWithImage:LoadImage(@"category_cart")];
        [_cartEmptyView addSubview:cartIcon];
        [cartIcon mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(_cartEmptyView);
            make.left.equalTo(_cartEmptyView).offset(80);
            make.width.equalTo(@22);
            make.height.equalTo(@22);
        }];
        
        KKLabel *contentLbl = [[KKLabel alloc]initWithBlock:^(KKLabel *lbl) {
            lbl.laText(@"Shopping cart is empty.",RGBColor(174, 174, 174),[UIFont systemFontOfSize:15.0],NSTextAlignmentLeft);
        }];
        [_cartEmptyView addSubview:contentLbl];
        [contentLbl mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(_cartEmptyView);
            make.left.equalTo(_cartEmptyView).offset(115);
            make.height.equalTo(@30);
            make.right.equalTo(_cartEmptyView).offset(-20);
        }];
        
        KKLabel *line = [[KKLabel alloc]initWithBlock:^(KKLabel *lbl) {
            
        }];
        line.backgroundColor = RGBColor(237, 237, 237);
        [_cartEmptyView addSubview:line];
        [line mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.equalTo(_cartEmptyView);
            make.height.equalTo(@1);
            make.bottom.equalTo(_cartEmptyView).offset(0);
            make.centerX.equalTo(_cartEmptyView);
        }];
    }
    self.cartTable.tableHeaderView = _cartEmptyView;
}
- (void)cartNoGoodsView
{
    
}
- (void)loginInClick:(UIButton *)sender
{
    UINavigationController *loginNavi = StoryBoardViewController(@"Login", @"LoginNavi");
    DDLoginViewController *loginVC = (DDLoginViewController *)loginNavi.topViewController;
    [self presentViewController:loginNavi animated:YES completion:nil];
    [loginVC userLoginSuccessCallBack:^{
        
    }];
}
- (void)layoutCartView
{
    self.cartStatus = DingDongCartStatusCheckOut;

    if (self.vcType == DingDongCartControllerTypePush) {
        [self setLeftBarItem];
    }

    self.checkoutView.hidden = NO;
    self.editView.hidden = YES;
    
    self.cartTable.sectionFooterHeight = 3;
    self.cartTable.backgroundColor = RGBColor(244, 244, 244);
    
    self.hotFooterView = [[UIView alloc]init];
    self.hotFooterView.frame = CGRectMake(0, 0, ScreenWidth, 400);
    self.cartTable.tableFooterView = self.hotFooterView;
    
    //测试
    UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc]init];
    //设置布局方向为垂直流布局
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    CGFloat width = (ScreenWidth-20)/2.0;
    CGFloat height = width+50;
    layout.itemSize = CGSizeMake(width, height);
    
    UICollectionView *collection = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 400) collectionViewLayout:layout];
    collection.delegate = self;
    collection.dataSource = self;
    collection.backgroundColor = [UIColor whiteColor];
    collection.scrollEnabled = NO;
    collection.backgroundColor = RGBColor(244, 244, 244);
    self.hotCollection = collection;
    [self.hotCollection registerClass:[DDCartHotSaleCollectionCell class] forCellWithReuseIdentifier:@"CartHotSaleCell"];
    [self.hotCollection registerClass:[DDHotSaleCollectionCustomeHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"CartHotSaleHeader"];
    [self.hotFooterView addSubview:_hotCollection];
    [_hotCollection mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(_hotFooterView);
    }];
    self.hotFooterView.frame = CGRectMake(0, 0, ScreenWidth, self.hotCollection.collectionViewLayout.collectionViewContentSize.height);
    self.cartTable.tableFooterView = self.hotFooterView;
    self.currentPage = 1;
    weak_Self(self);
    
    MJRefreshBackNormalFooter *footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        [weakSelf footerRefresh];
    }];
    [self.cartTable setMj_footer:footer];
    [self headerRefresh];
}
- (void)headerRefresh
{
    [self fetchHotSaleGoodsPull:YES success:^{
        
    }];
}
- (void)footerRefresh
{
    weak_Self(self);
    [self fetchHotSaleGoodsPull:NO success:^{
        [weakSelf.cartTable.mj_footer endRefreshing];
    }];
}
- (void)setCartStatus:(DingDongCartStatus)cartStatus
{
    _cartStatus = cartStatus;
    [self.cartTable reloadData];
}
- (void)editShopCartClick
{
    self.cartStatus = DingDongCartStatusEdit;
    self.checkoutView.hidden = YES;
    self.editView.hidden = NO;
    UIBarButtonItem *rightBar = [[UIBarButtonItem alloc]initWithTitle:@"Done" style:UIBarButtonItemStylePlain target:self action:@selector(doneShopCartClick)];
    rightBar.tintColor = [UIColor darkGrayColor];
    self.navigationItem.rightBarButtonItem = rightBar;
}
- (void)doneShopCartClick
{
    self.cartStatus = DingDongCartStatusCheckOut;
    self.checkoutView.hidden = NO;
    self.editView.hidden = YES;
    UIBarButtonItem *rightBar = [[UIBarButtonItem alloc]initWithTitle:@"Edit" style:UIBarButtonItemStylePlain target:self action:@selector(editShopCartClick)];
    rightBar.tintColor = [UIColor darkGrayColor];
    self.navigationItem.rightBarButtonItem = rightBar;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.cartSet.cartAry.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    DDCartObj *obj = self.cartSet.cartAry[section];
    return obj.cartList.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 120.0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 44.0;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    weak_Self(self);
    DDCartObj *obj = self.cartSet.cartAry[section];
    DDCartSectionHeader *header = [[DDCartSectionHeader alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 44)];
    header.backgroundColor = [UIColor whiteColor];
    [header selectSection:^(BOOL selected) {
        
        if (weakSelf.cartStatus == DingDongCartStatusCheckOut) {
            //结算状态
            [self storeSelected:!selected store:obj.store_id success:^{
                [obj.cartList enumerateObjectsUsingBlock:^(DDCartGoodsObj * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    if (!selected) {
                        obj.is_check = @1;
                    }else
                        obj.is_check = @0;
                }];
                if (!selected) {
                    obj.is_check = @1;
                }else{
                    obj.is_check = @0;
                }
                header.selectBtn.selected = !selected;
                [weakSelf loopCheckOutAllSelect];
            }];
        }else{
            //编辑状态
            if (selected) {
                obj.edit_is_check = @0;
            }else
                obj.edit_is_check = @1;
            
            [obj.cartList enumerateObjectsUsingBlock:^(DDCartGoodsObj * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if (selected) {
                    obj.edit_is_check = @0;
                }else
                    obj.edit_is_check = @1;
            }];
            [tableView reloadSections:[NSIndexSet indexSetWithIndex:section] withRowAnimation:UITableViewRowAnimationNone];
            header.selectBtn.selected = !header.selectBtn.selected;
            [self loopEditAllSelect];
        }

    }];
    header.storeName = obj.store_name;
    if (obj.activity_id.integerValue!=0) {
        DDActivityObj *activity = obj.activity[0];
        header.activityName = activity.activity_name;
    }
    
    if (self.cartStatus == DingDongCartStatusCheckOut) {
        if (obj.is_check.integerValue ==1) {
            header.selectBtn.selected = YES;
        }else
            header.selectBtn.selected = NO;
    }else{
        if (obj.edit_is_check.integerValue ==1) {
            header.selectBtn.selected = YES;
        }else
            header.selectBtn.selected = NO;
    }
    

    return header;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *indentifier = @"CartCell";
    
    DDCartTableCell *cell = [tableView dequeueReusableCellWithIdentifier:indentifier];
    
    if (!cell) {
        cell = [[DDCartTableCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:indentifier];
    }
    DDCartObj *obj = self.cartSet.cartAry[indexPath.section];
    DDCartGoodsObj *goods = obj.cartList[indexPath.row];
    [cell.goodsIcon sd_setImageWithURL:[NSURL URLWithString:goods.thumbnail] placeholderImage:nil];
    cell.goodsNameLbl.text = goods.name;
    if (!goods.goodprice) {
        cell.goodsPriceLbl.text = FormatString(@"$%@", goods.cartprice);
    }else{
        cell.goodsPriceLbl.text = FormatString(@"$%@", goods.goodprice);
    }
    cell.goodsSizeLbl.text = @"";
    cell.countTxf.text = FormatString(@"%@", goods.num);
    
    if (self.cartStatus == DingDongCartStatusCheckOut) {
        if (goods.is_check.integerValue == 1) {
            cell.cartSelectBtn.selected = YES;
        }else
            cell.cartSelectBtn.selected = NO;
    }else{
        if (goods.edit_is_check.integerValue == 1) {
            cell.cartSelectBtn.selected = YES;
        }else
            cell.cartSelectBtn.selected = NO;
    }
    
    weak_Self(self);
    [cell userCartSelect:^{
        
        if (weakSelf.cartStatus == DingDongCartStatusCheckOut) {
            //单个商品选中
            BOOL cartSelect = cell.cartSelectBtn.selected;
            [self cartSelected:!cartSelect cart:goods.cart_id success:^{
                if (!cartSelect) {
                    goods.is_check = @1;
                }else
                    goods.is_check = @0;
                cell.cartSelectBtn.selected = !cartSelect;
                //检察此店铺是不是应该选中
                __block NSInteger store_check = 1;
                [obj.cartList enumerateObjectsUsingBlock:^(DDCartGoodsObj * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    if (obj.is_check.integerValue == 0) {
                        store_check = 0;
                        *stop = YES;
                    }
                }];
                obj.is_check = @(store_check);
                [weakSelf loopCheckOutAllSelect];
            }];
        }else{
            //编辑状态单商品选中
            BOOL editSelect = cell.cartSelectBtn.selected;
            if (editSelect) {
                goods.edit_is_check = @0;
            }else
                goods.edit_is_check = @1;
            cell.cartSelectBtn.selected = !editSelect;
            
            __block NSInteger store_edit_check = 1;
            [obj.cartList enumerateObjectsUsingBlock:^(DDCartGoodsObj * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if (obj.edit_is_check.integerValue == 0) {
                    store_edit_check = 0;
                    *stop = YES;
                }
            }];
            obj.edit_is_check = @(store_edit_check);
            [tableView reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationNone];
            [self loopEditAllSelect];
        }

    }];
    
    //改变数量
    [cell userModifyNumber:^(NSString *num, NSString *lastNum) {
        [self modifyGoodsNumber:goods.cart_id num:num success:^{
            goods.num = @([num integerValue]);
            NSInteger min = [num integerValue]-[lastNum integerValue];
            weakSelf.totalMoney += min*[goods.goodprice floatValue];
            weakSelf.checkTotalLbl.text = FormatString(@"%.2f", weakSelf.totalMoney);
        } failure:^{
            goods.num = @([lastNum integerValue]);
            [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
        }];
    }];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    DDCartObj *obj = self.cartSet.cartAry[indexPath.section];
    DDCartGoodsObj *goods = obj.cartList[indexPath.row];
    DDGoodsDetailsViewController *vc = [[DDGoodsDetailsViewController alloc]init];
    vc.goods_id = goods.goods_id;
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    weak_Self(self);
    DDCartObj *obj = self.cartSet.cartAry[indexPath.section];
    DDCartGoodsObj *goods = obj.cartList[indexPath.row];
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [self deleteCart:FormatString(@"%@", goods.cart_id) success:^{
            [obj.cartList removeObject:goods];
            [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
            if (obj.cartList.count == 0) {
                [weakSelf.cartSet.cartAry removeObject:obj];
                [tableView deleteSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationFade];
            }
            if (weakSelf.cartSet.cartAry.count == 0) {
                [weakSelf checkCartEmpty];
            }
            [[SystemConfig shareInstance]updateCartCountSueesss:^(NSString *count) {
                
            }];
        }];
    }
}


#pragma mark --- 结算view的check和select
- (void)checkoutCartAllMoney
{
    __block CGFloat allMoney = 0;
    [self.cartSet.cartAry enumerateObjectsUsingBlock:^(DDCartObj * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [obj.cartList enumerateObjectsUsingBlock:^(DDCartGoodsObj * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {

            if (obj.is_check.integerValue == 1) {
                allMoney+=[obj.goodprice doubleValue]*[obj.num integerValue];
            }
            
        }];
        
    }];
    self.totalMoney = allMoney;
    self.checkTotalLbl.text = FormatString(@"$%.2f", allMoney);
}
- (void)loopCheckOutAllSelect
{
    //判断全部店铺的选中状态
    __block NSInteger allSelect = 1;
    [self.cartSet.cartAry enumerateObjectsUsingBlock:^(DDCartObj * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        if (obj.is_check.integerValue == 0) {
            allSelect = 0;
            *stop = YES;
        }
        
    }];
    if (allSelect == 1) {
        self.checkAllSelectStatus = YES;
    }else
        self.checkAllSelectStatus = NO;

    [self checkoutCartAllMoney];
}
- (void)setCheckAllSelectStatus:(BOOL)checkAllSelectStatus
{
    _checkAllSelectStatus = checkAllSelectStatus;
    if (checkAllSelectStatus) {
        self.checkSelectBtn.selected = YES;
    }else
        self.checkSelectBtn.selected = NO;
}
- (IBAction)checkSelectAllClick:(id)sender
{
    BOOL select = self.checkSelectBtn.selected;
    NSInteger allSelect = 0;
    if (select) {
        //取消全部选中
        allSelect = 0;
    }else{
        //全部选中
        allSelect = 1;
    }
    
    [self allSelect:allSelect success:^{
        if (allSelect == 0) {
            self.checkAllSelectStatus = NO;
        }else{
            self.checkAllSelectStatus = YES;
        }
        
        __block CGFloat allMoney = 0;
        [self.cartSet.cartAry enumerateObjectsUsingBlock:^(DDCartObj * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if (allSelect == 0) {
                obj.is_check = @0;
            }else{
                obj.is_check = @1;
            }
            
            [obj.cartList enumerateObjectsUsingBlock:^(DDCartGoodsObj * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if (allSelect == 0) {
                    obj.is_check = @0;
                }else{
                    obj.is_check = @1;
                    allMoney+=[obj.goodprice doubleValue]*[obj.num integerValue];
                }
            }];
            
        }];
        [self.cartTable reloadData];
        self.totalMoney = allMoney;
        self.checkTotalLbl.text = FormatString(@"$%.2f", allMoney);
        self.checkSelectBtn.selected = !select;
    }];
    
}
- (IBAction)checkoutClick:(id)sender
{
    weak_Self(self);
    __block BOOL haveSelect = NO;
    [self.cartSet.cartAry enumerateObjectsUsingBlock:^(DDCartObj * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
       [obj.cartList enumerateObjectsUsingBlock:^(DDCartGoodsObj * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
           if (obj.is_check.integerValue == 1) {
               haveSelect = YES;
               *stop = YES;
           }
       }];
        if (haveSelect) {
            *stop = YES;
        }
    }];
    if (!haveSelect) {
        [self showMessageHUD:@"You have not select goods" delayHide:1.0];
        return;
    }
    
    [self checkCartValid:^{
        DDCreateOrderViewController *vc = StoryBoardViewController(@"Order", @"DDCreateOrderViewController");
        vc.cartSet = self.cartSet;
        DDNavigationController *navi = [[DDNavigationController alloc]initWithRootViewController:vc];
        [weakSelf presentViewController:navi animated:YES completion:nil];
    } invalid:^{
        
    }];

}
#pragma mark --- 编辑view的collect和delete
- (void)setEditAllSelectStatus:(BOOL)editAllSelectStatus
{
    _editAllSelectStatus = editAllSelectStatus;
    if (editAllSelectStatus) {
        self.editSelectBtn.selected = YES;
    }else
        self.editSelectBtn.selected = NO;
}
- (void)loopEditAllSelect
{
    //判断全部店铺的选中状态
    __block NSInteger allSelect = 1;
    [self.cartSet.cartAry enumerateObjectsUsingBlock:^(DDCartObj * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        if (obj.edit_is_check.integerValue == 0) {
            allSelect = 0;
            *stop = YES;
        }
    }];
    if (allSelect == 1) {
        self.editAllSelectStatus = YES;
    }else
        self.editAllSelectStatus = NO;
    
}
- (IBAction)editDeleteClick:(id)sender
{
    if (self.editAllSelectStatus) {
        weak_Self(self);

        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Do you clear cart?" message:nil delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Clear", nil];
        [alert show];
        [alert click:^(NSInteger buttonIndex) {
            if (buttonIndex == 1) {
                //清空购物车
                [self clearCartSuccess:^{
                    [weakSelf.cartSet.cartAry removeAllObjects];
                    [weakSelf.cartTable reloadData];
                    [weakSelf checkCartEmpty];
                    [[SystemConfig shareInstance]setCartCount:0];
                }];
            }
        }];

    }else{
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Do you delete this products?" message:nil delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Delete", nil];
        [alert show];
        [alert click:^(NSInteger buttonIndex) {
            if (buttonIndex == 1) {
                //删除多个购物车
                __block NSString * editSelectCartId = @"";
                __block NSMutableArray *delAry = [[NSMutableArray alloc]initWithCapacity:0];
                [self.cartSet.cartAry enumerateObjectsUsingBlock:^(DDCartObj * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    [obj.cartList enumerateObjectsUsingBlock:^(DDCartGoodsObj * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                        if (obj.edit_is_check.integerValue == 1) {
                            editSelectCartId = [editSelectCartId stringByAppendingString:FormatString(@"%@", obj.cart_id)];
                            editSelectCartId = [editSelectCartId stringByAppendingString:@","];
                            [delAry addObject:obj];
                        }
                    }];
                }];
                
                if (editSelectCartId.length!=0) {
                    editSelectCartId = [editSelectCartId substringToIndex:editSelectCartId.length-1];
                }
                KKLog(@"编辑选择的cart %@",editSelectCartId);
                weak_Self(self);
                [self deleteCart:editSelectCartId success:^{
                    [weakSelf fetchCartList];
                    [[SystemConfig shareInstance]updateCartCountSueesss:^(NSString *count) {
                        
                    }];
                }];

            }
        }];
    }
}
- (IBAction)editCollectClick:(id)sender
{
    
}
- (IBAction)editSelectAllClick:(id)sender
{
    BOOL editSelect = self.editSelectBtn.selected;
    weak_Self(self);
    [self.cartSet.cartAry enumerateObjectsUsingBlock:^(DDCartObj * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (editSelect) {
            obj.edit_is_check = @0;
            weakSelf.editAllSelectStatus = NO;
        }else{
            obj.edit_is_check = @1;
            weakSelf.editAllSelectStatus = YES;
        }
        [obj.cartList enumerateObjectsUsingBlock:^(DDCartGoodsObj * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if (editSelect) {
                obj.edit_is_check = @0;
            }else
                obj.edit_is_check = @1;
        }];
    }];
    [self.cartTable reloadData];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.clickBlock) {
        alertView.clickBlock(buttonIndex);
    }
}
#pragma mark --- UICollectionViewDelegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.hotSet.goodsGroup.count;
}
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    DDGoodsObj *goods = self.hotSet.goodsGroup[indexPath.row];
    DDCartHotSaleCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CartHotSaleCell" forIndexPath:indexPath];
    cell.goodsPriceLbl.text = FormatString(@"$%.2f", [goods.price doubleValue]);
    [cell.goodsIcon sd_setImageWithURL:[NSURL URLWithString:goods.thumbnail] placeholderImage:nil];
    cell.goodsNameLbl.text = goods.name;
    [cell userHotSaleAddCart:^{
        
    }];
    return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    DDGoodsObj *goods = self.hotSet.goodsGroup[indexPath.row];
    DDGoodsDetailsViewController *vc = [[DDGoodsDetailsViewController alloc]init];
    vc.goods_id = goods.goods_id;
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}
#pragma mark ---- UICollectionViewDelegateFlowLayout

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat width = (ScreenWidth-10)/2.0;
    CGFloat height = width+66;
    return (CGSize){width,height};
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    return (CGSize){ScreenWidth,44};
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(5, 2, 5, 2);
}


- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 5.f;
}


- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 5.f;
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    
    UICollectionReusableView *reusableView = nil;
    
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        DDHotSaleCollectionCustomeHeaderView *header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"CartHotSaleHeader" forIndexPath:indexPath];
        header.title =@"Pick of the week";
        header.showLine = NO;
        reusableView = header;
    }
    
    return reusableView;
}

#pragma mark --- 接口
//购物车列表
- (void)fetchCartList
{
    weak_Self(self);
    [self showHUD];
    [[self.manager getCartList]subscribeNext:^(id x) {
        weakSelf.cartSet = x;
        [weakSelf reloadCartInfo];
    } error:^(NSError *error) {
        
    } completed:^{
        [weakSelf hideHUD];
    }];
}
- (void)reloadCartInfo
{
    [self.cartSet.cartAry enumerateObjectsUsingBlock:^(DDCartObj * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        for (DDCartGoodsObj *goods in obj.cartList) {
            if (goods.is_check.integerValue == 0) {
                obj.is_check = 0;
                break;
            }
        }
    }];
    
    [self loopCheckOutAllSelect];
    [self checkoutCartAllMoney];
    [self.cartTable reloadData];
    [self checkCartEmpty];
    
    if (self.cartSet.cartAry.count == 0) {
        self.checkoutView.hidden = YES;
        self.editView.hidden = YES;
        self.checkoutViewHeight.constant = 0;
        self.navigationItem.rightBarButtonItem = nil;
    }else{
        self.checkoutView.hidden = NO;
        self.checkoutViewHeight.constant = 50;
        [self setRightItemBar];
    }
}
- (void)storeSelected:(BOOL)select store:(NSNumber *)store_id success:(void(^)())block
{
    NSInteger check = 0;
    if (select) {
        check = 1;
    }
    weak_Self(self);
    [[self.manager cancelSelectedStore:store_id is_check:check]subscribeNext:^(id x) {
        if (block) {
            block();
        }
        [weakSelf.cartTable reloadData];
    } error:^(NSError *error) {
        
    } completed:^{
        
    }];
}
- (void)cartSelected:(BOOL)select cart:(NSNumber *)cart_id success:(void(^)())block
{
    NSInteger check = 1;
    if (select) {
        check = 0;
    }
    weak_Self(self);
    [[self.manager cancelSelectedCart:cart_id is_check:check]subscribeNext:^(id x) {
        if (block) {
            block();
        }
        [weakSelf.cartTable reloadData];
    } error:^(NSError *error) {
        
    } completed:^{
        
    }];
}
- (void)deleteCart:(NSString *)cart_id success:(void(^)())block
{
    [[self.manager deleteCartObj:cart_id]subscribeNext:^(id x) {
        if (block) {
            block();
        }
    } error:^(NSError *error) {
        
    } completed:^{
        
    }];
}
- (void)modifyGoodsNumber:(NSNumber *)cart_id num:(NSString *)num success:(void(^)())block failure:(void(^)())errBlock
{
    weak_Self(self);
    [[self.manager addCartObjNum:cart_id num:num]subscribeNext:^(id x) {
        if (block) {
            block();
        }
        [weakSelf.cartTable reloadData];
    } error:^(NSError *error) {
        if (errBlock) {
            errBlock();
        }
    } completed:^{
        
    }];
}
- (void)clearCartSuccess:(void(^)())block
{
    [[self.manager clearCart]subscribeNext:^(id x) {
        if (block) {
            block();
        }
    } error:^(NSError *error) {
        
    } completed:^{
        
    }];
}
- (void)checkCartValid:(void(^)())block  invalid:(void(^)())invalid
{
    [[self.manager cartValidCheck]subscribeNext:^(id x) {
        if (block) {
            block();
        }
    } error:^(NSError *error) {
        NSString *msg = error.userInfo[@"msg"];
        [self showMessageHUD:msg delayHide:3.0];
        if (invalid) {
            invalid();
        }
    } completed:^{
        
    }];
}
- (void)allSelect:(NSInteger)select success:(void(^)())block
{
    [[self.manager cancelSelectedAll:select]subscribeNext:^(id x) {
        if (block) {
            block();
        }
    } error:^(NSError *error) {
        
    } completed:^{
        
    }];
}
#pragma mark --- 获取热销商品
- (void)fetchHotSaleGoodsPull:(BOOL)pull success:(void(^)())block
{
    if (pull) {
        self.currentPage = 1;
    }
    weak_Self(self);
    [[self.homeManager getHomeVerticalGoodsListWithPageNo:self.currentPage size:kPageSize]subscribeNext:^(id x) {
        if (block) {
            block();
        }
        if (pull) {
            [weakSelf.hotSet.goodsGroup removeAllObjects];
            weakSelf.hotSet = x;
        }else{
            DDHotSaleSet *set = x;
            [weakSelf.hotSet.goodsGroup addObjectsFromArray:set.goodsGroup];
        }
        weakSelf.currentPage+=1;
        [weakSelf reloadCartHotSale];
    } error:^(NSError *error) {
        
    } completed:^{
        
    }];
}
- (void)reloadCartHotSale
{
    CGFloat width = (ScreenWidth-10)/2.0;
    CGFloat height = width+66;
    
    NSInteger count = self.hotSet.goodsGroup.count;
    CGFloat colHeight = 0;
    if (count%2 == 0) {
        NSInteger row = count/2;
        colHeight = row*(height+5);
    }else{
        NSInteger row = count/2+1;
        colHeight = row*(height+5);
    }
    
    self.hotFooterView.frame = CGRectMake(0, 0, ScreenWidth, colHeight+45);
    self.cartTable.tableFooterView = self.hotFooterView;
    [self.hotCollection reloadData];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
